from django.shortcuts import render

# Create your views here.
import json

from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response
from api.utils_material import get_material_subtype_by_id, is_used_material_subtype
from api.models import MaterialSubType, UploadRecord
from api.serializers import MaterialSubTypeSerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action
from django.db.models import Q

from api.mylogger import logger


class MaterialSubtypeViewSet(viewsets.ModelViewSet):
    table_name = MaterialSubType._meta.db_table
    serializer_class = MaterialSubTypeSerializer

    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['material_type', 'material_subtype', 'name_zh', 'category'],
                                  properties={
                                      "kind": openapi.Schema(type=openapi.TYPE_STRING, description="官方sys 本地local"),
                                      "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="素材类型"),
                                      "material_subtype": openapi.Schema(type=openapi.TYPE_STRING, description="素材子分类"),
                                      "name_zh": openapi.Schema(type=openapi.TYPE_STRING, description="子分类中文名"),
                                      "category": openapi.Schema(type=openapi.TYPE_STRING, description="素材前端的内部分类"),
                                  }, )

    @swagger_auto_schema(operation_id='添加素材子分类', tags=['materialsubtype'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def material_subtype_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        serializer = MaterialSubTypeSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增素材子分类成功")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除素材子分类', tags=['materialsubtype'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="素材子分类表的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def material_subtype_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        if db_id is None:
            return failed_response_with_data(msg="没有id参数")
        one_obj = get_material_subtype_by_id(db_id)
        material_type = one_obj.get('material_type', '')
        material_subtype = one_obj.get('material_subtype', '')
        is_used = is_used_material_subtype(material_type, material_subtype)
        if is_used:
            return failed_response_with_data(data=None, msg="素材子分类已经被使用, 删除不了")

        deleted_cnt, _ = MaterialSubType.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "info": "删除" + str(deleted_cnt) + "条记录!",
            "rows_deleted": deleted_cnt
        }
        return success_response_with_data(res_data, msg="删除记录成功!")

    @swagger_auto_schema(operation_id='单条素材子分类信息', tags=['materialsubtype'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="素材子分类的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def material_subtype_one(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        try:
            qry = MaterialSubType.objects.get(id=db_id)
            serializer = MaterialSubTypeSerializer(qry)
            return success_response_with_data(serializer.data, msg=self.table_name + "查询对象成功!")
        except ObjectDoesNotExist:
            return failed_response_with_data(None, msg=self.table_name + f"未查到id为{db_id}的素材子分类!")

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['id', 'material_type', 'material_subtype', 'name_zh', 'category'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部Id"),
                                          "kind": openapi.Schema(type=openapi.TYPE_STRING, description="官方sys 本地local"),
                                          "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="素材类型"),
                                          "material_subtype": openapi.Schema(type=openapi.TYPE_STRING, description="素材子分类"),
                                          "name_zh": openapi.Schema(type=openapi.TYPE_STRING, description="子分类中文名"),
                                          "category": openapi.Schema(type=openapi.TYPE_STRING, description="素材前端的内部分类"),
                                      }, )

    @swagger_auto_schema(operation_id='修改素材子分类', tags=['materialsubtype'], request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def material_subtype_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")
        one_obj = get_material_subtype_by_id(db_id)
        material_type = one_obj.get('material_type', '')
        material_subtype = one_obj.get('material_subtype', '')
        is_used = is_used_material_subtype(material_type, material_subtype)
        if is_used:
            return failed_response_with_data(data=None, msg="素材子分类已经被使用, 修改不了")

        serializer = MaterialSubTypeSerializer(data=data)
        if serializer.is_valid():
            try:
                db_ret = serializer.update(instance=MaterialSubType.objects.get(id=db_id), validated_data=data)
                logger.debug(f"db_ret {db_ret}")

                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改记录成功!")
            except ObjectDoesNotExist:
                return failed_response_with_data(msg=self.table_name+f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='素材子分类列表查询', tags=['materialsubtype'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "kind": openapi.Schema(type=openapi.TYPE_STRING, description="官方sys 本地local"),
                                 "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="素材类型"),
                                 "category": openapi.Schema(type=openapi.TYPE_STRING, description="内部素材类型"),
                                 "query": openapi.Schema(type=openapi.TYPE_STRING, description="名称的部分信息"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def material_subtype_list(self, request):
        # is_frontend = get_is_frontend(request)

        data = json.loads(request.body.decode('utf8'))
        current_page = data.get("pagenum", 1)
        page_size = data.get("pagesize", 10)
        query = data.get("query", '')
        material_type = data.get("material_type", '')
        material_subtype = data.get("material_subtype", '')
        category = data.get("category", '')
        kind = data.get("kind", '')

        if current_page < 1:
            current_page = 1
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = MaterialSubType.objects
            if kind != '':
                objects = objects.filter(kind=kind)
            if material_type != '':
                objects = objects.filter(material_type=material_type)
            if material_subtype != '':
                objects = objects.filter(material_subtype=material_subtype)
            if category != '':
                objects = objects.filter(category=category)
            if len(query):
                objects = objects.filter(Q(name_zh__icontains=query) | Q(material_subtype__icontains=query) | Q(material_type__icontains=query))

            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        material_subtype_list = MaterialSubTypeSerializer(rows, many=True).data
        return list_response(material_subtype_list, total, page_size, current_page, self.table_name)



